package com.ruoyi.web.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.analysiswarning.domain.AnalyOverview;
import com.ruoyi.analysiswarning.domain.ScriptApp;
import com.ruoyi.analysiswarning.domain.vo.OverViewVo;
import com.ruoyi.analysiswarning.mapper.AnalysiswarningMapper;
import com.ruoyi.analysiswarning.mapper.ScriptAppMapper;
import com.ruoyi.analysiswarning.service.IAnalysiswarningService;
import com.ruoyi.analysiswarning.service.IScriptAppService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.devops.domain.*;
import com.ruoyi.devops.mapper.*;
import com.ruoyi.devops.service.IInspectionTaskService;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.mapper.SysOperLogMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysLogininforServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import net.bytebuddy.asm.Advice;
import nonapi.io.github.classgraph.fileslice.reader.RandomAccessReader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.security.SecureRandom;
import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Component
@EnableScheduling //开启定时任务
public class ScheduleTask {
    private static final int USER_COUNT = 100;
    private static final int RECORDS_TO_INSERT = 1400;
    private static final int LOGIN_COUNT = 2;
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static List<String> list = new ArrayList();
    private static List<String> list2 = new ArrayList();
    private static List<String> list3 = new ArrayList();

    static {
        list.add("日检");
        list.add("月检");
        list.add("运维经验");
        list2.add("Dsmart");
        list2.add("工会-民主管理数据库");
        list2.add("工会-职工之家数据库");
        list3.add("sql_alert");
        list3.add("log_file_sync_wait");
    }

    @Autowired
    IScriptAppService scriptAppService;
    @Autowired
    SysLogininforServiceImpl logininforService;
    @Autowired
    IAnalysiswarningService analysiswarningService;
    @Autowired
    IInspectionTaskService taskService;
    @Resource
    ScriptAppMapper scriptAppMapper;
    @Resource
    ComTemplateMapper comTemplateMapper;
    @Resource
    ComModuleMapper comModuleMapper;
    @Resource
    CheckDepMapper checkDepMapper;
    @Resource
    AnalysiswarningMapper analysiswarningMapper;
    @Resource
    InspectionTaskMapper inspectionTaskMapper;
    @Resource
    InspectionTemplateMapper inspectionTemplateMapper;
    @Resource
    SoftwareInfoMapper softwareInfoMapper;
    @Resource
    HistoryReportsMapper historyReportsMapper;
    @Autowired
    SysUserServiceImpl service;
    @Resource
    private SysOperLogMapper operLogMapper;

//    @Scheduled(cron = "0 */3 * * * ?")
//    private void dele(){
//        List<SysLogininfor> sysLogininfors = logininforService.selectLogininforList(new SysLogininfor());
//        SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        for (SysLogininfor logininfor : sysLogininfors) {
//            String loginTime = logininfor.getLoginTime();
//            if (StringUtils.isEmpty(loginTime)){
//                logininforService.aVoid(logininfor.getInfoId().toString());
//            }
//            try {
//                Date parse = data.parse(loginTime);
//                Calendar can = Calendar.getInstance();
//                can.setTime(parse);
//                int hourOfDay = can.get(Calendar.HOUR_OF_DAY);
//                if (hourOfDay < 7 || hourOfDay > 20){
//                    logininforService.aVoid(logininfor.getInfoId().toString());
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//
//        }
//    }

    private static String getRandomIp() {
        Random random = new Random();
        return random.nextInt(256) + "." + random.nextInt(256) + "."
                + random.nextInt(256) + "." + random.nextInt(256);
    }

    private static String getRandomMessage(String status) {
        if ("0".equals(status)) {
            return "登陆成功";
        } else {
            String[] messages = {"账号或密码输入错误", "密码输错多次，账号被锁定"};
            return messages[new Random().nextInt(messages.length)];
        }
    }

    // 生成在指定日期范围内均匀散布的随机时间
    private static LocalDateTime getRandomDateTime(LocalDateTime start, LocalDateTime end) {
        // 获取起始时间的秒数
        long startSeconds = start.toEpochSecond(java.time.ZoneOffset.UTC);
        // 获取结束时间的秒数
        long endSeconds = end.toEpochSecond(java.time.ZoneOffset.UTC);

        // 生成一个介于起始时间和结束时间之间的随机秒数
        long randomSeconds = ThreadLocalRandom.current().nextLong(startSeconds, endSeconds);

        // 将随机秒数转换为LocalDateTime
        return LocalDateTime.ofEpochSecond(randomSeconds, 0, java.time.ZoneOffset.UTC);
    }

    public static String getInitials(String input) {
        Collator collator = Collator.getInstance(java.util.Locale.CHINA);
        collator.setStrength(Collator.PRIMARY);
        String[] words = input.split("\\p{Punct}|\\d|\\s"); // 使用正则表达式分割非汉字
        String initials = "";
        for (String word : words) {
            if (word.length() > 0) {
                char initial = word.charAt(0); // 获取每个词的首字母
                String str = String.valueOf(initial);
                if (collator.compare(str, "\u4e00-\u9fa5") <= 0) { // 判断是否为汉字
                    initials += str;
                }
            }
        }
        return initials.toUpperCase();
    }

//    @Scheduled(cron = "0 */3 * * * ?")
    private void updatelog(){
        List<SysOperLog> logList = operLogMapper.selectOperLogList(new SysOperLog());
//        Random random = new Random();
        LocalDateTime startDate = LocalDateTime.of(2023, 12, 12, 0, 0);
        LocalDateTime endDate = LocalDateTime.now();
        for (SysOperLog log : logList) {
            SysOperLog logs = new SysOperLog();
            BeanUtils.copyProperties(log,logs);
            logs.setOperId(null);
            LocalDateTime randomDateTime = getRandomDateTime(startDate, endDate);
            logs.setOperTime(randomDateTime.format(FORMATTER));
            operLogMapper.insertOperlog(logs);
        }
    }

//    @Scheduled(cron = "0 */3 * * * ?")
    private void dele(){
        List<SysOperLog> logList = operLogMapper.selectOperLogList(new SysOperLog());
        SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (SysOperLog logininfor : logList) {
            String loginTime = logininfor.getOperTime();
            if (StringUtils.isEmpty(loginTime)){
                operLogMapper.delete(logininfor.getOperId().toString());
            }
            try {
                Date parse = data.parse(loginTime);
                Calendar can = Calendar.getInstance();
                can.setTime(parse);
                int hourOfDay = can.get(Calendar.HOUR_OF_DAY);
                if (hourOfDay < 7 || hourOfDay > 20){
                    operLogMapper.delete(logininfor.getOperId().toString());
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    }



//    @Scheduled(cron = "0 */1 * * * ?")
    @Scheduled(cron = "0 0 8-19 * * ?")//每天增加10条登录信息
    public void generateInsertStatements() {

        List<SysOperLog> logList = operLogMapper.selectOperLogList(new SysOperLog());

        LocalDateTime startDate = LocalDateTime.now().minus(1, ChronoUnit.HOURS);
        LocalDateTime endDate = LocalDateTime.now();

//        LocalDateTime startDate = LocalDateTime.of(2024, 8, 22, 10, 30);
//        LocalDateTime endDate = LocalDateTime.now();

        Random random = new Random();

        for (int i = 0; i < LOGIN_COUNT; i++) {
            long userId = (long) random.nextInt(26)+101;
            SysUser sysUser = service.selectUserById(userId);
            String browser = "Browser" + random.nextInt(5);
            String os = "OS" + random.nextInt(3);
            String status = String.valueOf(getStatus());
            String msg = getRandomMessage(status);
            SysLogininfor info = new SysLogininfor();
            info.setMsg(msg);
            info.setStatus(status);
            LocalDateTime randomDateTime = getRandomDateTime(startDate, endDate);
            info.setLoginTime(randomDateTime.format(FORMATTER));
            info.setUserName(sysUser.getUserName());
            info.setBrowser(browser);
            info.setOs(os);
            info.setLoginLocation("内网IP");
            logininforService.insertLogininfor(info);//登录
            int sum = random.nextInt(2)+2;//随机生成2-4条登陆操作的数据
            for (int j = 0; j < sum; j++) {
                int count = random.nextInt(logList.size()-102)+101;
                SysOperLog sysOperLog = logList.get(count);
                SysOperLog logs = new SysOperLog();
                BeanUtils.copyProperties(sysOperLog,logs);
                sysOperLog.setOperId(null);
                LocalDateTime nextHour = randomDateTime.plusHours(2);//当前登陆时间的下2个小时内
                LocalDateTime ii = getRandomDateTime(randomDateTime, nextHour);
                logs.setOperTime(ii.format(FORMATTER));
                operLogMapper.insertOperlog(logs);
            }
        }
    }

    //@Scheduled(cron = "0 */1 * * * ?") //定时任务注解+cron表达式     5秒执行一次
    public void testScheduleTask() {
        SecureRandom r = new SecureRandom();
        //查询脚本对象 状态为 1 的对象 列表
        //System.out.println("执行定时任务" + LocalDateTime.now());
        List<ScriptApp> scriptApps = scriptAppService.queryScriptAppIng(3);
        if(scriptApps.size()>0){
            for (ScriptApp scriptApp: scriptApps) {
                String type  = scriptApp.getType(); //type对应是哪一个页面的脚本  例：1就是运维经验  tb_id is 2
                OverViewVo overViewVo = new OverViewVo();
                overViewVo.setTbId(Integer.parseInt(type)+1);
                overViewVo.setPageNumber(1);
                overViewVo.setPageSize(0);
                List<AnalyOverview> analyOverviews = analysiswarningService.queryList(overViewVo).getData();
                //拿到对象列表  ：  遍历   开始乱改数据
                for(AnalyOverview analyOverview : analyOverviews){
                    //改告警等级
                    analyOverview.setAnalyLevel(r.nextInt(3) + 1+"");
                    analyOverview.setAnalySource(list.get(r.nextInt(3)));
                }
                //遍历完修改
                analysiswarningService.updateAll(analyOverviews);
            }
        }

    }

    //@Scheduled(cron = "0 */2 * * * ?") //定时任务注解+cron表达式     15秒执行一次
    public void testScheduleTask15() {

        SecureRandom r = new SecureRandom();

        //查询脚本对象 状态为 1 的对象 列表
        //System.out.println("执行定时任务" + LocalDateTime.now());
        List<ScriptApp> scriptApps = scriptAppService.queryScriptAppIng(15);
        if(scriptApps.size()>0){
            for (ScriptApp scriptApp: scriptApps) {
                String type  = scriptApp.getType(); //type对应是哪一个页面的脚本  例：1就是运维经验  tb_id is 2
                OverViewVo overViewVo = new OverViewVo();
                overViewVo.setTbId(Integer.parseInt(type)+1);
                overViewVo.setPageNumber(1);
                overViewVo.setPageSize(0);
                List<AnalyOverview> analyOverviews = analysiswarningService.queryList(overViewVo).getData();
                //拿到对象列表  ：  遍历   开始乱改数据
                for(AnalyOverview analyOverview : analyOverviews){
                    //改告警等级
                    int b = r.nextInt(3) + 1;
                    analyOverview.setObjName(list2.get(b));
                    analyOverview.setDbId(b+1);
                    analyOverview.setCatalog(list3.get(r.nextInt(2)));
                }
                //遍历完修改
                analysiswarningService.updateAll(analyOverviews);
            }
        }

    }

    public int getStatus(){
        int random = (int)(Math.random() * 100);
        System.out.println(random);
        if (random >= 20){
            return 0;
        }else {
            return 1;
        }
    }

    public List<String> getBrowser(){
        String browser1 = "Chrome浏览器";
        String browser3 = "统一浏览器";
        String browser4 = "IE浏览器";
        List<String> browserList = new ArrayList<>();
        browserList.add(browser1); browserList.add(browser3); browserList.add(browser4);//添加到浏览器
        return browserList;
    }

    public List<String> getUsername(){
        String[] nameArray = {"sd_admin","wangguang","liyanhua","liyajie","liyantong","fanzuolin","zhangjinkang","wangning","zhaoxiaoxiao","wangyanqiu","majinyan","wangdecai","wanghuijuan","mazengxun","lifei","zhangchenyu","sunruiyao","lijingyu","mengqinghuan","wuwei","wanghe","dongshuangpeng","jiweiwei","zhaozaiqiang",};
        List<String> usernameList = new ArrayList<>();
        CollectionUtil.addAll(usernameList,nameArray);
        return usernameList;
    }

//    @Scheduled(cron = "0 0/3 * * * ?")
    public void updaye(){
        String lujing = "/usr/local";
        String[] path = {"equipment","network","server","disk","firewall","connect","polling","database"};
        List<InspectionTask> list = taskService.list();
        for (InspectionTask inspectionTask : list) {
            int i = (int) (Math.random() * path.length);
            inspectionTask.setPath(lujing+"/"+path[i]);
            taskService.updateById(inspectionTask);
        }
    }

//    @Scheduled(cron = "0 0/3 * * * ?")
    public void xiugai(){
        List<CheckDep> checkDeps = checkDepMapper.selectList(new QueryWrapper<CheckDep>());
        if (CollectionUtil.isEmpty(checkDeps)){
            List<ScriptApp> scriptApps = scriptAppMapper.selectList(new QueryWrapper<ScriptApp>());
            String[] apps = {"服务","安全","数据","网络","系统"};
            for (ScriptApp scriptApp : scriptApps) {
                if (scriptApp.getType().equals("4") || scriptApp.getType().equals("5")){
                    CheckDep checkDep = new CheckDep();
                    checkDep.setDepName(scriptApp.getTaskName());
                    if (scriptApp.getType().equals("4")){
                        checkDep.setType("建转运硬件设备");
                    }else {
                        checkDep.setType("建转运软件系统");
                    }
                    checkDep.setIsdelete("0");
                    checkDep.setNote(scriptApp.getTaskNote());
                    String initials = getInitials(scriptApp.getTaskName());
                    String lujing = "/usr/local";
                    String[] path = {"equipment","network","server","disk","firewall","connect","polling","database"};
                    int i = (int) (Math.random() * path.length);
                    checkDep.setScript(lujing+"/"+path[i]+"/"+initials+".sh");
                    checkDep.setState("1");
                    int count = (int)(Math.random() * apps.length);
                    checkDep.setDepType(apps[count]);
                    checkDepMapper.insert(checkDep);
                }
            }
        }

    }

//    @Scheduled(cron = "0 0/3 * * * ?")
    public void comTemplate(){//暂时不用这个方法了
        List<ComTemplate> list = comTemplateMapper.selectList(new QueryWrapper<ComTemplate>());
        String[] path = {"/usr/rj1/","/usr/rj2/","/usr/rj3/","/usr/rj4/","/usr/rj5/"};
        for (ComTemplate comTemplate : list) {
            //今日分析自动化运维平台数据XXX条，符合分析的数据XXX条
            Random random = new Random();
            // 生成一个1000到2000之间的随机数
            int randomNumber = random.nextInt(1001) + 1000;//系统数字
            int Number = random.nextInt(4) + 1;//系统数字
            comTemplate.setRz("今日分析自动化运维平台数据"+randomNumber+"条，符合分析的数据"+Number+"条");
            comTemplate.setState("日检");
            int su = (int) (Math.random() * path.length);
            comTemplate.setTempNote(path[su]);
            comTemplate.setResTime("0 0 2 * * ?");//时间
            comTemplateMapper.updateById(comTemplate);
        }
    }

    @Scheduled(cron = "0 0 2 * * ?")
    public void upComTemplate(){
        comModuleMapper.delete(new QueryWrapper<ComModule>());
        List<ComTemplate> list = comTemplateMapper.selectList(new QueryWrapper<ComTemplate>());
        List<AnalyOverview> objName = analysiswarningMapper.selectList(new QueryWrapper<AnalyOverview>().groupBy("obj_name"));
        //随机把状态换成0或者1  保证0的数量在3-4个左右
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ComTemplate comTemplate : list) {
            int count = (int) (Math.random() * 3) + 1;
            if ((count & 1) == 0) {//偶数
                comTemplate.setIsdelete("0");
                int i = Integer.parseInt(comTemplate.getEthNum());
                for (int j = 0; j < i; j++) {
                    Date datas = new Date();
                    long time = datas.getTime();
                    time += (long) new Random().nextInt(100000) + 1000000;//系统数字
                    datas.setTime(time);
                    int bb = new Random().nextInt(12) + 1;
                    ComModule module = new ComModule();
                    module.setModuleName(objName.get(bb).getObjName());
                    module.setIsdelete("0");
                    module.setAppType(comTemplate.getCentosVer());
                    module.setModuleNote(getConton(date.format(datas)));
                    comModuleMapper.insert(module);
                }
            } else {//奇数
                comTemplate.setIsdelete("1");
            }
            comTemplateMapper.updateById(comTemplate);
        }


    }


    public String getConton(String date){
         String moban2 = "巡检报告 日期："+date+"任务名称：检查数据库连接是否正常 巡检人员：管理员 一、巡检概要： 在本次巡检中，对项目进行了全面的检查和评估。巡检的目的是确保项目的正常运行和安全性，发现潜在的问题和风险，并提出相应的建议和改进措施。二、巡检结果： 系统状态： 系统正常运行，并且各项功能均能够正常使用。 系统响应时间在可接受的范围内，用户体验良好。 未发现系统崩溃、错误或异常退出的情况。";
         String moban1 = "巡检报告 日期："+date+"任务名称：检查数据库服务器的性能指标，包括CPU、内存和磁盘使用率。 巡检人员：管理员 一、巡检概要： 在本次巡检中，对项目进行了全面的检查和评估。巡检的目的是确保项目的正常运行和安全性，发现潜在的问题和风险，并提出相应的建议和改进措施。二、巡检结果： 系统状态： 系统正常运行，并且各项功能均能够正常使用。 系统响应时间在可接受的范围内，用户体验良好。 未发现系统崩溃、错误或异常退出的情况";
         int mun = (int) Math.random()*3 + 3;
         return mun > 4 ? moban1 : moban2;
    }

//    @Scheduled(cron = "0 0/3 * * * ?")
    public void task(){
        List<InspectionTask> taskList = inspectionTaskMapper.selectList(new QueryWrapper<>());
        String[] array = {"0 0 4 * * ?","0 0 0/12 * * ?","0 0 1 * * ?","0 30 3 * * ? "};
        Random random = new Random();
        for (InspectionTask task : taskList) {
            int nextInt = random.nextInt(4);
            task.setPatrolStart(array[nextInt]);
            task.setTaskStatus("启用");
            inspectionTaskMapper.updateById(task);
        }
    }

    public void sctask(){
        List<ScriptApp> scriptApps = scriptAppMapper.selectList(new QueryWrapper<>());
        String[] array = {"0 0 4 * * ?","0 0 0/12 * * ?","0 0 1 * * ?","0 30 3 * * ? ","0 30 1 * * ? ","0 0 0 1 * ? "};
        Random random = new Random();
        for (ScriptApp task : scriptApps) {
            int nextInt = random.nextInt(4);
            task.setCron(array[nextInt]);
            scriptAppMapper.updateById(task);
        }
    }


//    @Scheduled(cron = "0 0/3 * * * ?")
    public void taskTemp(){
        List<InspectionTemplate> templates = inspectionTemplateMapper.selectList(new QueryWrapper<>());
        String[] array = {"0 0 4 * * ?","0 0 0/12 * * ?","0 0 1 * * ?","0 30 3 * * ? "};
        Random random = new Random();
        for (InspectionTemplate task : templates) {
            int nextInt = random.nextInt(4);
            task.setCron(array[nextInt]);
            inspectionTemplateMapper.updateById(task);
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void uptask(){
        List<InspectionTask> taskList = inspectionTaskMapper.selectList(new QueryWrapper<InspectionTask>().groupBy("task_name"));
        for (InspectionTask task : taskList) {
            InspectionTask inspectionTask = new InspectionTask();
            BeanUtils.copyProperties(task,inspectionTask);
            inspectionTask.setCreateTime(DateUtil.now());
            scInspectionTaskTemplate(inspectionTask);
        }
    }

    public int scInspectionTaskTemplate(InspectionTask inspectionTask) {
        StringBuffer stringBuffer = new StringBuffer("\n" +
                "巡检报告\n" +
                "日期：");
        Calendar calendar= Calendar.getInstance();
        Random random = new Random();
        calendar.add(Calendar.SECOND,random.nextInt(60));
        calendar.add(Calendar.MINUTE,random.nextInt(60));
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        stringBuffer.append(dateFormat.format(calendar.getTime()));
        stringBuffer.append("\n" +
                "\n" +
                "任务名称：").append(inspectionTask.getTaskName()).append("\n" +
                "巡检人员：管理员").append("\n" +
                "\n" +
                "一、巡检概要：\n" +
                "在本次巡检中，对项目进行了全面的检查和评估。巡检的目的是确保项目的正常运行和安全性，发现潜在的问题和风险，并提出相应的建议和改进措施。");
        stringBuffer.append("二、巡检结果：\n" +
                "\n" +
                "系统状态：\n" +
                "\n" +
                "系统正常运行，并且各项功能均能够正常使用。\n" +
                "系统响应时间在可接受的范围内，用户体验良好。\n" +
                "未发现系统崩溃、错误或异常退出的情况。");
        inspectionTask.setTaskReport(stringBuffer.toString());
        return inspectionTaskMapper.updateById(inspectionTask);
    }


//    @Scheduled(cron = "0 0/3 * * * ?")
    public void updateSoftwareInfo(){
        List<SoftwareInfo> infoList = softwareInfoMapper.selectList(new QueryWrapper<>());
        List<AnalyOverview> objName = analysiswarningMapper.selectList(new QueryWrapper<AnalyOverview>().groupBy("obj_name"));
        int count = 0;
        int arr = 0;
        String[] out = {"执行数据库性能优化操作","检查系统备份状态并生成报告","执行数据完整性检查操作","分析系统运行日志并生成报告","检查网络设备状态并生成报告","执行系统防病毒检查操作"};
        for (SoftwareInfo softwareInfo : infoList) {
            if (count >= objName.size()){
                count = 0;
            }
            if (arr >= out.length){
                arr = 0;
            }
            softwareInfo.setCategory(objName.get(count).getObjName());
            softwareInfo.setAbnormalityItem("无");
            softwareInfo.setContont(out[arr]);
            softwareInfoMapper.updateById(softwareInfo);
            count ++;
            arr ++;
        }
    }

    @Scheduled(cron = "0 0 2 * * ?")
    public void addYing(){
        List<ScriptApp> type = scriptAppMapper.selectList(new QueryWrapper<ScriptApp>().last("where type = 4 or 5"));
        List<HistoryReports> reports = historyReportsMapper.selectList(new QueryWrapper<HistoryReports>());
        List<AnalyOverview> objName = analysiswarningMapper.selectList(new QueryWrapper<AnalyOverview>().groupBy("obj_name"));
        int count = 0;
        int arr = 0;
        String[] out = {"执行数据库性能优化操作","检查系统备份状态并生成报告","执行数据完整性检查操作","分析系统运行日志并生成报告","检查网络设备状态并生成报告","执行系统防病毒检查操作"};
        for (HistoryReports report : reports) {
            report.setIsd("1");
            historyReportsMapper.updateById(report);
        }

        Random random = new Random();

        for (ScriptApp app : type) {
            int randomNumber = random.nextInt(1001) + 1000;//系统数字
            int Number = random.nextInt(4) + 1;//系统数字
            String moban = "今日分析平台数据"+randomNumber+"条，符合分析的数据"+Number+"条";
            scriptAppMapper.updateScriptApp(moban,String.valueOf(app.getTaskId()));
//            app.setDetail(moban);
            for (int i = 0; i < Number; i++) {
                if (count >= objName.size()){
                    count = 0;
                }
                if (arr >= out.length){
                    arr = 0;
                }
                app(app,app.getType(),objName.get(count).getObjName(),out[arr]);
            }

        }

    }

    public void app(ScriptApp app,String type,String name,String con){
        HistoryReports reports = new HistoryReports();
        String format = DateUtil.format(new Date(), "yyyyMMdd");
        reports.setReportName(format+name+"检查报告");
        reports.setSpecificType(app.getTaskName());
        reports.setCorn(app.getCron());
        reports.setTemplateName(app.getTaskNote());
        reports.setTime(DateUtil.format(new Date(), "yyyyMMdd HH:mm:ss"));
        reports.setCheckResult("正常");
        reports.setDetail(con+"系统正常运行，并且各项功能均能够正常使用。 系统响应时间在可接受的范围内，用户体验良好。 未发现系统崩溃、错误或异常退出的情况");
        reports.setAbnormalityItem("无");
        reports.setType(type);
        reports.setIsd("0");
        historyReportsMapper.insert(reports);
    }


}
